<?php

namespace App;

use App\Scopes\StatusScope;
use App\Traits\TimeFormat;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable {

	use Notifiable, HasApiTokens, TimeFormat;

	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = [
		'name', 'email', 'password', 'nick_name', 'avatar', 'website', 'description', 'is_admin', 'status', 'email_notify_enabled', 'github', 'weibo',
	];

	/**
	 * The attributes that should be hidden for arrays.
	 *
	 * @var array
	 */
	protected $hidden = [
		'password', 'remember_token',
	];

	protected $casts = [
		'is_admin' => 'boolean',
		'status' => 'boolean',
		'email_notify_enabled' => 'boolean',
	];

	public static function boot() {
		parent::boot();
		static::addGlobalScope(new StatusScope());
	}

	public function findForPassport($username) {
		if (filter_var($username, FILTER_VALIDATE_EMAIL)) {
			return self::where('email', $username)->first();
		}
		return self::where('name', $username)->first();
	}

	public function isApproveing($item_id) {
		return $this->approveItems->contains($item_id);
	}

	public function approveItems() {
		return $this->belongsToMany(Item::class, 'approves')->withTimestamps();
	}

	public function approves() {
		return $this->hasMany(Approve::class);
	}

	public function items() {
		return $this->hasMany(Item::class);
	}

	public function comments() {
		return $this->hasMany(Comment::class);
	}

	public function messages() {
		return $this->hasMany(Message::class);
	}

	public function setPasswordAttribute($value) {
		$this->attributes['password'] = bcrypt($value);
		//change confirm_code when change password or create new user
		$this->attributes['confirm_code'] = md5($this->attributes['password']);
	}

	public function getAvatarAttribute($value) {
		if (is_null($value) || empty($value)) {
			return '/avatar/default.jpg';
		}
		return $value;
	}
}
